package com.multiplayer.listener;
 
import java.text.ParseException;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.multiplayer.dao.IReservationDao;
import com.multiplayer.dao.impl.ReservationDaoImpl;
 
/**
 * Listener的方式在后台执行一线程
 * 
 * @author Champion.Wong
 * 
 */
@WebListener
public class MyListener implements ServletContextListener {
	private MyThread myThread;
 
	public void contextDestroyed(ServletContextEvent e) {
		System.out.println("执行contextDestroyed");
		if (myThread != null && myThread.isInterrupted()) {
			myThread.interrupt();
		}
	}
 
	public void contextInitialized(ServletContextEvent e) {
		System.out.println("执行contextInitialized");
		String str = null;
		if (str == null && myThread == null) {
			myThread = new MyThread();
			myThread.start(); // servlet 上下文初始化时启动 socket
		}
	}
}
/**
 * 自定义一个 Class 线程类继承自线程类，重写 run() 方法，用于从后台获取并处理数据
 * 
 * @author Champion.Wong
 * 
 */
class MyThread extends Thread {
	public void run() {
		while (!this.isInterrupted()) {// 线程未中断执行循环
			try {
				Thread.sleep(5000); //每隔2000ms执行一次
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
//			 ------------------ 开始执行 ---------------------------
			IReservationDao reservationDao=new ReservationDaoImpl();
			try {
				reservationDao.autoProcessReservation();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}